<template>
  <div class="merchant-list">
    <div class="shops-header">
      <el-icon><Location /></el-icon>
      <span class="shops-title">附近商家</span>
    </div>

    <div class="shop-list">
      <el-skeleton :loading="loading" animated :count="6">
        <template #template>
          <div class="shop-skeleton">
            <el-skeleton-item variant="image" style="width: 80px; height: 80px;" />
            <div class="skeleton-content">
              <el-skeleton-item variant="h3" style="width: 50%" />
              <el-skeleton-item variant="text" style="width: 80%" />
              <el-skeleton-item variant="text" style="width: 60%" />
            </div>
          </div>
        </template>
        <template #default>
          <div v-if="merchants.length">
            <div
                v-for="merchant in merchants"
                :key="merchant.merchantId"
                class="shop-item"
                @click="goToShop(merchant)"
            >
              <div class="shop-left">
                <img :src="getAvatarUrl(merchant.avatar_path)" class="shop-image" alt="商家头像">
              </div>
              <div class="shop-right">
                <div class="shop-header">
                  <h4 class="shop-name ellipsis">{{ merchant.name }}</h4>
                  <div class="shop-tags">
                    <el-tag v-if="merchant.distance <= 10" size="small" type="success">附近</el-tag>
                    <el-tag v-else size="small" type="info">较远</el-tag>
                  </div>
                </div>

                <div class="shop-description ellipsis" v-if="merchant.description">
                  {{ merchant.description }}
                </div>

                <div class="shop-address ellipsis">
                  <el-icon><Location /></el-icon>
                  <span>{{ merchant.address }}</span>
                </div>

                <div class="shop-delivery">
                  <div class="delivery-info">
                    <span>¥{{ merchant.leastprice }}起送</span>
                  </div>
                  <div class="delivery-time">
                    <span>{{ getDeliveryTime(merchant.distance) }}</span>
                    <span class="divider">/</span>
                    <span>{{ merchant.distance.toFixed(2) }}km</span>
                  </div>
                </div>
              </div>
            </div>

            <el-pagination
                v-if="total > pageSize"
                v-model:current-page="currentPage"
                :page-size="pageSize"
                layout="prev, pager, next"
                :total="total"
                @current-change="fetchMerchants"
                class="pagination"
            />
          </div>
          <div v-else class="empty-shops">
            <img src="@/assets/shop_back.svg" alt="no shops">
            <p>附近暂无商家</p>
          </div>
        </template>
      </el-skeleton>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useCookies } from 'vue3-cookies';
import { Location } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus'; // 导入 ElMessage
import axios from 'axios';
import { API_BASE_URL } from '@/config';
const { cookies } = useCookies();
const router = useRouter();

const loading = ref(true);
const merchants = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
import defaultMerchantImage from '@/assets/default-merchant.jpg'; // 导入默认头像图片
// 获取商家头像完整URL
const getAvatarUrl = (path) => {
  if (!path) return defaultMerchantImage;
  return `${import.meta.env.VITE_API_BASE_URL}${path}`;
};

// 根据距离估算配送时间
const getDeliveryTime = (distance) => {
  if (distance <= 1) return '20-30分钟';
  if (distance <= 3) return '30-40分钟';
  if (distance <= 5) return '40-50分钟';
  return '50-60分钟';
};

// 获取商家列表
const fetchMerchants = async () => {
  try {
    loading.value = true;

    // 从cookie获取经纬度
    const latitude = cookies.get('latitude');
    const longitude = cookies.get('longitude');

    if (!latitude || !longitude) {
      throw new Error('无法获取位置信息');
    }

    const response = await axios.post(`${API_BASE_URL}/merchant/getmerchantlist`,null,{
      params:{
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        userLongitude: parseFloat(longitude),
        userLatitude: parseFloat(latitude)}
    });

    merchants.value = response.data;
    total.value = response.total || response.data.length;
  } catch (error) {
    console.error('获取商家列表失败:', error);
    ElMessage.error('获取商家列表失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 跳转到商家详情
const goToShop = (merchant) => {
  if (!merchant || !merchant.merchantId) {
    console.error('无效的商家对象或缺少merchantId:', merchant);
    return;
  }

  router.push({
    path: `/ShopDetail/${merchant.merchantId}`,
    query: {
      address:merchant.address,
      phone:merchant.merchantphone,
      leastprice:merchant.leastprice,
      description:merchant.description,
      name: merchant.name || '',
      avatar: merchant.avatar_path || '',
      distance: merchant.distance || 0
    }
  });
};

// 组件挂载时自动获取商家数据
onMounted(() => {
  fetchMerchants();
});
</script>

<style scoped>
.merchant-list {
  flex: 1;
  margin-top: 0.625rem;
  background-color: white;
  width: 100%; /* 宽度100% */
  max-width: 100%; /* 移除最大宽度限制 */
}

/* 商家列表项样式调整 */
.shop-item {
  width: 100%;
  padding: 0.9375rem 1.25rem; /* 增加左右内边距 */
}

.shops-header {
  padding: 0.625rem; /* 10px -> 0.625rem */
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
}

.shops-header .el-icon {
  color: #999;
  margin-right: 0.3125rem; /* 5px -> 0.3125rem */
}

.shops-title {
  font-size: 0.875rem; /* 14px -> 0.875rem */
  color: #999;
}

.shop-list {
  padding: 0 0.625rem; /* 10px -> 0.625rem */
}

.shop-skeleton {
  display: flex;
  padding: 0.9375rem 0; /* 15px -> 0.9375rem */
  border-bottom: 1px solid #eee;
}

.skeleton-content {
  flex: 1;
  padding-left: 0.625rem; /* 10px -> 0.625rem */
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

.shop-item {
  display: flex;
  padding: 0.9375rem 0; /* 15px -> 0.9375rem */
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.shop-left {
  width: 5rem; /* 80px -> 5rem */
  height: 5rem; /* 80px -> 5rem */
  margin-right: 0.625rem; /* 10px -> 0.625rem */
  flex-shrink: 0;
}

.shop-image {
  width: 100%;
  height: 100%;
  border-radius: 0.25rem; /* 4px -> 0.25rem */
  object-fit: cover;
}

.shop-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-width: 0;
}

.shop-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.3125rem; /* 5px -> 0.3125rem */
}

.shop-name {
  font-size: 1rem; /* 16px -> 1rem */
  color: #333;
  margin: 0;
  max-width: 70%;
}

.shop-tags .el-tag {
  margin-left: 0.3125rem; /* 5px -> 0.3125rem */
}

.shop-description {
  font-size: 0.75rem; /* 12px -> 0.75rem */
  color: #999;
  margin-bottom: 0.3125rem; /* 5px -> 0.3125rem */
}

.shop-address {
  display: flex;
  align-items: center;
  font-size: 0.75rem; /* 12px -> 0.75rem */
  color: #666;
  margin-bottom: 0.3125rem; /* 5px -> 0.3125rem */
}

.shop-address .el-icon {
  margin-right: 0.1875rem; /* 3px -> 0.1875rem */
  font-size: 0.875rem; /* 14px -> 0.875rem */
}

.shop-delivery {
  display: flex;
  justify-content: space-between;
  font-size: 0.75rem; /* 12px -> 0.75rem */
  color: #666;
}

.delivery-info {
  display: flex;
  align-items: center;
}

.divider {
  margin: 0 0.3125rem; /* 5px -> 0.3125rem */
  color: #ddd;
}

.empty-shops {
  padding: 3.125rem 0; /* 50px -> 3.125rem */
  text-align: center;
}

.empty-shops img {
  width: 6.25rem; /* 100px -> 6.25rem */
  height: 6.25rem; /* 100px -> 6.25rem */
  opacity: 0.5;
}

.empty-shops p {
  margin-top: 0.625rem; /* 10px -> 0.625rem */
  color: #999;
}


</style>
